#!/bin/bash

function check_component_state(){
    n_process=0
    i=1
    echo "Check process status of components for openGauss cluster."
    for ((i=1;i<=5;i++)); do
        n_cm_agent_process=$(ps -ef | grep cm_agent | grep -v  grep | wc -l)
        n_cm_server_process=$(ps -ef | grep cm_server | grep -v  grep | wc -l)
        n_gaussdb_process=$(ps -ef | grep gaussdb | grep $PGDATA | wc -l)
        echo "$n_cm_agent_process $n_cm_server_process $n_gaussdb_process"
        if [ $n_cm_agent_process -eq 1 ] && [ $n_cm_server_process -eq 1 ] && [ $n_gaussdb_process -eq 1 ];then
            echo "The components CM agent, server and openGauss instance is running at ${hostname}." 
            n_process=3
            echo "Wait 30 seconds to ensure replication process built in openGauss cluster." 
            echo
            sleep 30
            break
        else
            echo "Abnormal porcess $n_cm_agent_process $n_cm_server_process $n_gaussdb_process"
            sleep 30
            continue
        fi
    done
    # It can be removed if we find a way to ensure CM Server in healthy status.
    # Be care of to check the CM server cluster's status
    #sleep 60
    #echo "Check CM server cluster's status, and exit if code is not 0." 
    #cm_ctl query
}

check_component_state
